<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: #000;
        }

        .ball {
            position: absolute;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <script>
    //  属性：球颜色backgroundColor、球的坐标x,y、球透明度opacity、球半径r、球的dom元素
    //  方法：小球更新update，初始化init
    //  怎么实现多个小球的动画？
    //  将每个小球实例放在一个数组中，通过定时器去遍历这个数组，调用每个实例的update方法
    
    let ballList = [];

    function Ball(x,y){
        // 小球的坐标
        this.x=x;
        this.y=y;

        // 小球半径
        this.r=20
        // 透明度
        this.opacity=1
        // 颜色随机
        let colorlist = []
        for(let i=0;i<3;i++){
            colorlist.push(parseInt(Math.random() * 256));
        }
        this.backgroundColor=`rgb(${colorlist[0]},${colorlist[1]},${colorlist[2]})`
         //  dX dY
         do {
                this.dX = parseInt(Math.random() * 10 - 5);
                this.dY = parseInt(Math.random() * 10 - 5);
            } while (this.dX === 0 && this.dY === 0)
            //  小球的初始化
            this.init();
            //  将实例记录到数组中，方便遍历去更新
            ballList.push(this);
    }
    Ball.prototype.init=function(){
        this.dom=document.createElement("div");
        this.dom.classList.add("ball");
        this.dom.style.width=this.r * 2+"px";
        this.dom.style.height=this.r * 2+"px";
        this.dom.style.backgroundColor=this.backgroundColor;
        this.dom.style.left=this.x-this.r +"px"
        this.dom.style.top=this.y-this.r +"px"
        document.body.appendChild(this.dom)
    }   

    Ball.prototype.update=function(){
        this.x+=this.dX
        this.y+=this.dY
        this.r+=0.5;
        this.opacity -=0.01;
        this.dom.style.opacity=this.opacity
        this.dom.style.width=this.r * 2+"px";
        this.dom.style.height=this.r * 2+"px";
        this.dom.style.left=this.x-this.r +"px"
        this.dom.style.top=this.y-this.r +"px"

        if(this.opacity<=0){
            this.dom.remove();
            for(let i=0;i<ballList.length;i++){
                if(ballList[i]===this){
                    ballList.splice(i,1);
                }
            }
        }
    }
    
    document.addEventListener("mousemove",function(e){
        new Ball(e.clientX,e.clientY)
    })

    setInterval(function(){
        for(let i=0;i<ballList.length;i++){
            ballList[i].update()
        }
    },20);
    </script>
</body>
</html>